package com.linkdood.app.web.rest;

import com.linkdood.app.dto.PhoneCodeDTO;
import com.linkdood.app.service.VerifyCodeService;
import com.linkdood.app.utils.ResourceUtil;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

/**
 * 验证码接口
 */
@Api(value = "验证码接口", tags = {"验证码接口"})
@Slf4j
@RestController
@RequestMapping("/api/phone")
public class VerifyCodeResource {

    private final VerifyCodeService verifyCodeService;

    public VerifyCodeResource(VerifyCodeService verifyCodeService) {
        this.verifyCodeService = verifyCodeService;
    }

    /**
     * 发送验证码
     * @param phone 手机号
     * @return bid 业务id
     */
    @PostMapping("/send-code/{phone}")
    public ResponseEntity<?> sendCode(@PathVariable String phone) {
        String bid = verifyCodeService.sendCode(phone);
        Map<String, String> result = new HashMap<>(1);
        result.put("bid", bid);
        return ResponseEntity.ok(result);
    }

    /**
     * 校验验证码
     * @param req 验证码入参
     */
    @PostMapping("/check-code")
    public ResponseEntity<?> checkCode(@Valid @RequestBody PhoneCodeDTO req) {
        verifyCodeService.checkVerifyCode(req.getBid(), req.getPhone(), req.getCode());
        return ResponseEntity.ok(ResourceUtil.success());
    }

    /**
     * 获取验证码
     * @param bid 业务id
     * @return 验证码
     */
    @GetMapping("/{bid}")
    public ResponseEntity<?> getCode(@PathVariable String bid) {
        String code = verifyCodeService.getCode(bid);
        Map<String, String> result = new HashMap<>(1);
        result.put("value", code);
        return ResponseEntity.ok(result);
    }
}

